/**
 * Created by wenguangjia on 2017/8/14.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('commLogConsoleController', commLogConsoleController);
    commLogConsoleController.$inject = ['$scope', 'searchService', 'toaster'];
    function commLogConsoleController($scope, searchService, toaster) {
        var notify = function (type, title, message) {
            toaster.pop(type, title, message);
        };

        $scope.param = {progress:0,order:false};
        var array = new Array();//数据源
        var isLoadMore = true;
        var requestData = null;
        $scope.commlog = null;
        //循环遍历，取key值username和password的value
        for (var i = localStorage.length - 1; i >= 0; i--) {
            if (localStorage.key(i) == "commlogObj") {
                $scope.commlog = JSON.parse(localStorage.getItem(localStorage.key(i)));
                requestData = generateData();
            }
        }

        $scope.progress=[{ename:"all",cname:"全部",seq:0},{ename:"SRC",cname:"源service调用请求",seq:100},{ename:"XCOM_WRITE_SEND",cname:"XCOM写入send表",seq:200},{ename:"XCOM_SEND",cname:"XCOM发",seq:210},{ename:"XBUS_RECV",cname:"BUS收",seq:300},{ename:"XBUS_SEND",cname:"BUS发",seq:310},{ename:"XCOM_RECV",cname:"XCOM收",seq:400},{ename:"XCOM_WRITE_RECV",cname:"XCOM写入recv表",seq:410},{ename:"XCOM_CALL_SVC",cname:"XCOM调用svc",seq:420},{ename:"XCOM->DEST",cname:"接收电文svc开始",seq:500},{ename:"XCOM->DEST",cname:"接收电文svc结束",seq:510},{ename:"SUCCESS",cname:"XCOM调用svc结束",seq:600}];
        $scope.progressOptions = {
            template: '<span class="k-state-default">{{dataItem.cname}}---{{dataItem.ename}}</span>'
        };
        //绑定字段处理
        $scope.progressOptions.dataSource = new kendo.data.DataSource({
            transport: {
                read: function (e) {
                    e.success($scope.progress);
                }
            },
        });

        $scope.query = function(){
            array.length=0;
            requestData = generateData();
            if($scope.param.progress != 0){
                var obj = {"term": {"progress_seq": $scope.param.progress}};
                requestData.query.bool.must.push(obj);
            }
            if($scope.param.order){
                requestData.sort[0].progress_seq.order='desc';
                requestData.sort[1]['@timestamp'].order='desc';
            }
            $scope.gridOptions.dataSource.read();
        };

        //文档高度
        function getDocumentTop() {
            var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                documentScrollTop = document.documentElement.scrollTop;
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }

        //可视窗口高度
        function getWindowHeight() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }

        //滚动条滚动高度
        function getScrollHeight() {
            var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }

        window.onscroll = function () {
            //监听事件内容
            if ((getDocumentTop() + getWindowHeight() == getScrollHeight()) && isLoadMore) {
                //当滚动条到底时,这里是触发内容
                //异步请求数据,局部刷新dom
                //requestData.from+=sourceCount;
                requestData.from += 30;
                $scope.gridOptions.dataSource.read();
            }
        };

        function generateData(){
            var data = {
                "query": {
                    "bool": {
                        "must": [
                            {"term": {"uuid": $scope.commlog.uuid}}
                        ],
                        "filter": []
                    }
                },
                "sort": [
                    {"progress_seq":{"order":"asc"}},{"@timestamp": {"order": "asc"}}
                ],
                "size": 30,
                "from": 0
            };
            return data;
        }


        /**
         * Grid
         * @type {[*]}
         */
        var columns = [
            {field: "progress_seq", title: "序列号",width:"90px"},
            {field: "timestamp", title: "时间",width:"200px"},
            {field: "logmsg", title: "日志内容"}
        ];

        $scope.gridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu: true
        };
        $scope.gridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    searchService.query(requestData, null, null).then(function (resp) {
                        console.log(resp);
                        var data = resp.data.hits.hits;
                        data.length == 30 ? isLoadMore = true : isLoadMore = false;
                        angular.forEach(data, function (item) {
                            item._source.timestamp = getDate(item._source['@timestamp']);
                            array.push(item._source);
                        });
                        e.success(array);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            // requestStart: function (e) {
            //     if (requestData==null) {
            //         e.preventDefault();
            //     }
            // },
            // schema: {
            //     model: $scope.deployModel
            // },
            batch: true
        });
    }
})();
